import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/hj_model/mine/ExchangeRecordModel.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';

class MineExchangeCodeLogic extends GetxController {
  final int type; //0-填写邀请码 1-填写兑换码
  TextEditingController controller = TextEditingController();
  List<ExchangeRecordModel> groupList = [];
  bool isLoadingHistoryData = true;
  RefreshController refreshController = RefreshController();
  int currentPage = 1;

  MineExchangeCodeLogic({this.type = 0});

  @override
  onReady() {
    super.onReady();
    if (type == 1) loadData();
  }

  loadData({int page = 1}) async {
    try {
      final res = await MineService.getExchangeRecord(page, 20);
      if (res != null && res.data != null) {
        if (page == 1) groupList.clear();
        currentPage = page;
        groupList.addAll(res.data ?? []);
      }
      refreshController.refreshCompleted();
      (res?.total ?? 0) > (res?.data?.length ?? 0) ? refreshController.loadComplete() : refreshController.loadNoData();
    } catch (e) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      debugLog(e);
    }
    update();
    isLoadingHistoryData = false;
  }

  loadMoreData() => loadData(page: currentPage + 1);

  void onExChangeCode() async {
    if (controller.text.isEmpty) {
      showToast('请输入${type == 0 ? '邀请码' : '兑换码'}');
      return;
    }

    if (type == 1) {
      try {
        LoadingAlertWidget.show();
        bool ret = await MineService.postExchangeCode(controller.text);
        LoadingAlertWidget.cancel();
        if (ret == true) {
          controller.text = "";
          globalStore.updateUserInfo();
          showToast("兑换成功");
          loadData();
        }
      } catch (e) {
        LoadingAlertWidget.cancel();
        debugLog(e);
      }
    } else if (type == 0) {
      try {
        LoadingAlertWidget.show();
        bool ret = await MineService.getProxyBind(controller.text);
        LoadingAlertWidget.cancel();
        if (ret == true) {
          globalStore.meInfo?.inviterCode = controller.text;
          globalStore.updateUserInfo();
          showToast("绑定成功");
          Get.back(result: true);
        }
      } catch (e) {
        LoadingAlertWidget.cancel();
        debugLog(e);
      }
    }
  }
}
